<template>
  <div style="display: flex; align-items: center">
    <input
      type="checkbox"
      :checked="todo.done"
      @change="changeChecked(todo.id)"
    />
    <span v-show="!todo.isEdit">{{ todo.name }}</span>
    <input
      type="text"
      v-show="todo.isEdit"
      :value="todo.name"
      @blur="blurFunc(todo, $event)"
      ref="updateNameInput"
    />
    <div class="button-group">
      <button
        v-show="!todo.isEdit"
        @click="updateObj(todo, $event)"
        class="edit-btn"
      >
        编辑
      </button>
      <button @click="deleteObj(todo.id)" class="delete-btn">删除</button>
    </div>
  </div>
</template>

<script>
import pubsub from "pubsub-js";

export default {
  name: "MyItem",
  props: ["todo"],
  methods: {
    deleteObj(id) {
      pubsub.publish("deleteTask", id);
    },
    changeChecked(id) {
      this.$bus.$emit("changeTaskDone", id);
    },
    updateObj(todo, e) {
      if (todo.hasOwnProperty("idEdit")) {
        todo.isEdit = true;
      } else {
        this.$set(todo, "isEdit", true);
      }
      this.$nextTick(function () {
        this.$refs.updateNameInput.focus();
      });
    },
    blurFunc(todo, e) {
      todo.isEdit = false;
      if (!e.target.value.trim()) {
        alert("输入不能为空");
        return;
      }
      this.$bus.$emit("updateTitle", todo.id, e.target.value);
    },
  },
};
</script>

<style>
</style>